<template>
  <div style="flex: 90%; margin-top: 20px; margin-left: 20px">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="最高价">
        <el-input
          v-model="formInline.price"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="计算天数">
        <el-input
          v-model="formInline.dayCount"
          placeholder="请输入"
          clearable
        />
      </el-form-item>
      <el-form-item label="偏移天数">
        <el-input v-model="formInline.difDays" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="增长百分比(%)">
        <el-input v-model="formInline.upSum" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="红次数">
        <el-input v-model="formInline.upCount" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onFucus">关注列表</el-button>
        <el-button type="primary" @click="handleLoadRecordSure">加载数据</el-button>
        <el-button type="primary" @click="onLoadRecord">数据记录</el-button>
      </el-form-item>
    </el-form>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="选日期">
        <el-date-picker
                v-model="formInline.dateTime"
                type="date"
                placeholder="Pick a day"
                size="large"
                @change="handleDateChange"
            />
      </el-form-item>
      <el-form-item label="涨跌幅(%)">
        <el-input v-model="formInline.upDown" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearchByDate">查询</el-button>
      </el-form-item>
    </el-form>
    
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="股票代码">
        <el-input
          v-model="formInline.code"
          style="width: 240px"
          placeholder="input stock code"
          @update:model-value="onInputChange"
      />
      <el-select  @change="handleSelectIndustry($event)" v-model="industry_type_str[formInline.industry_type_index]" placeholder="Select" class="select" style="margin-left: 20px;">
          <el-option v-for="item in industry_type" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button type="primary" @click="onLoadIndustryStockList" style="margin-left: 20px;">板块股票列表</el-button>
    </el-form-item>
      
    </el-form>

    <el-table
      v-loading="loading"
      row-key="code"
      :data="tableDataIndustryStockList"
      style="width: 100%"
    >
    <el-table-column prop="orderIndex" label="序号" :width="50" >
            <template #default="scope">
                <el-text >{{scope.$index + 1}}</el-text>
            </template>
    </el-table-column>
    <el-table-column style="color: #990000;" prop="industryType" label="板块" :width="180" >
            <template #default="scope">
                <el-text style="color: #333333;font-weight: bold;font-size: 13px;">{{scope.row.industryType}}</el-text>
            </template>
        </el-table-column>
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="code" label="代码" width="180" />
    </el-table>

    <el-table
      v-loading="loading"
      ref="tableRef"
      row-key="code"
      :data="tableData"
      style="width: 100%"
    >
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="code" label="代码" width="180" />
      <el-table-column prop="currentPrice" label="价格" width="180"/>    
      <el-table-column prop="focus" label="操作" width="380" >
        <template #default="scope">
          <el-button  @click="handleEdit(scope.$index, scope.row)" 
          :type="['','success','primary','danger'][scope.row.focus]"  plain>
            {{ ['未关注','已关注','观察中','Vip关注'][scope.row.focus]}}
          </el-button>
          <el-button  @click="handleCopy(scope.$index, scope.row)" class="btn-copy" width="180" plain>
            复制
          </el-button>
          <el-button  @click="handlerAddIndustry(scope.$index, scope.row)" class="btn-copy" width="180" plain>
            添加到板块
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-table
      v-loading="loading"
      ref="tableRef"
      row-key="code"
      :data="tableDataRecordData"
      style="width: 100%"
    >
      <el-table-column prop="name" label="名称" width="180" />
      <el-table-column prop="code" label="代码" width="180" />
      <el-table-column prop="intA" label="完成" width="180">
        <template #default="scope">
                <el-text :style="{color:getDoneColor(scope.row.intA)}">{{ getDoneStr(scope.row.intA) }}</el-text>
            </template>
      </el-table-column>

      <el-table-column prop="focus" label="操作" width="180" >
        <template #default="scope">
          <el-button  @click="handleEdit(scope.$index, scope.row)" 
          :type="['','success','primary','danger'][scope.row.focus]"  plain>
            {{ ['未关注','已关注','观察中','Vip关注'][scope.row.focus]}}
          </el-button>
          <el-button  @click="handleCopy(scope.$index, scope.row)" class="btn-copy" width="180" plain>
            复制
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
  
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import type { TableColumnCtx, TableInstance } from "element-plus";
import { reactive } from "vue";
import axios from "axios";
import { countdownEmits, ElMessage, ElMessageBox } from "element-plus";
import ClipboardJS from 'clipboard';
import { useStore } from 'vuex';

const formInline = reactive({
  dayCount: "",
  upSum: "0",
  upCount: "0",
  difDays: "0",
  code: "",
  price: "100",

  upDown:0.0,
  dateTime: '',
  industry_type_index:0,
});
           
const onSubmit = () => {
  if (formInline.dayCount == "") {
    ElMessage({
      message: "天数必须大于0",
      type: "warning",
    });
    return;
  }
  loading.value = true;
  console.log(formInline);
  console.log("submit!");
  axios
    .get(
      "api/plat/stock/getStockList?dayCount=" +
        formInline.dayCount +
        "&upSum=" +
        formInline.upSum +
        "&upCount=" +
        formInline.upCount +
        "&difDays=" +
        formInline.difDays +
        "&price=" + formInline.price
    )
    .then((response) => {
      loading.value = false;
      if (response.data.status == 300) {
        ElMessage({
          message: "数据量较大，只截取前100条",
          type: "warning",
        });
      }
      tableData.value = response.data.data;
      console.log("数量" + response.data.data.length);
    })
    .catch((error) => {
      loading.value = false;
      console.error("Error fetching data:", error);
    });
};

const onFucus = () => {
  console.log(formInline);
  console.log("submit!");
  axios
    .get("api/plat/stock/getStockFocusList?focus=0")
    .then((response) => {
      tableData.value = response.data.data;
      console.log(tableData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const getDoneColor = (intA:number) => {
    return ["#67C23A","#F56C6C","#666666"][intA]
 };

const getDoneStr = (intA:number) => {
  return ["已完成","未完成","暂不执行"][intA]
};

const onSearh = (str: string, type: number) => {
  console.log("submit!");
  const encodedName = encodeURIComponent(str);
  const api = "api/plat/stock/getStockListByCode?type=" + type + (type === 1 ?  "&code=" + str : "&name=" + encodedName);
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableData.value = response.data.data;
      console.log(tableData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onSearchByDate = () => {
  console.log("submit!");
  loading.value = true;
  const api = "api/plat/stock/getStockListByDateUpDown?date=" + formInline.dateTime + "&upDown=" + formInline.upDown;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      loading.value = false;
      tableData.value = response.data.data;
      console.log(tableData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const handleLoadRecordSure = () => {
      // 显示确认框
    ElMessageBox.confirm(
      '是否确认加载数据？', '加载数据',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning' // 弹窗类型，可以是 'success', 'info', 'warning', 'error'
      }
      ).then(() => {
        onAddRecord()
      }).catch(() => {
       
      });
    };
    
const onLoadRecord = () => {
  console.log("submit!");
  const api = "api/plat/stockDataRecord/findPageList/1/200?dateTime=" + formInline.dateTime;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableDataRecordData.value = response.data.data.list;
      console.log(tableDataRecordData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onLoadIndustryStockList = () => {
  console.log("submit!");
  const encodedIndustryStr = encodeURIComponent(industry_type_str[formInline.industry_type_index]);
  const api = "api/plat/stockIndustry/findPageList//1/200?industryType=" + encodedIndustryStr;
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableDataIndustryStockList.value = response.data.data.list;
      console.log(tableDataIndustryStockList);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const onAddRecord = () => {
  console.log("submit!");
  const api = "api/plat/stockDataRecord/loadDataRecord";
  console.log(api) 
  axios
    .get(api)
    .then((response) => {
      tableDataRecordData.value = response.data.data.list;
      console.log(tableDataRecordData);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};


const onUpdateFoucus = (id: number, focus: number) => {
  console.log("submit!");
  axios
    .get("api/plat/stockName/updateFocus?id=" + id + "&focus=" + focus)
    .then((response) => {
      // console.log(response.status);
    })
    .catch((error) => {
      console.error("Error fetching data:", error);
    });
};

const increaseNow = ref("")
const increaseList = ref([])
const fetchData = () => {
    console.log("submit!");
    const api = "api/plat/stock/getStockNowData?stockCode=002640&queryTime=2024-12-04&allCount=1000";
    console.log(api) 
    axios
      .get(api)
      .then((response) => {
        const result = response.data;
        console.log("请求结果:", result);
        if (result.status == 200) {
          console.log("请求成功:", result);
          increaseList.value = response.data.data;
          var i = 0;
          
          setInterval(() => {
            
            increaseNow.value = increaseList.value[i].increase;
            console.log("数据:", increaseNow.value);
            i++;
            if (i >= increaseList.value.length) {
              i = 0;
            }

          }, 1000);
        } else {
          console.error("请求失败:");
        }
      })
      .catch((error) => {
        console.error("Error fetching data:", error);
      });
  };

interface StockName {
  id: number;
  name: string;
  code: string;
  focus: number;
  riskLevel: number;
  marketType: string;
  stockType: string;
  currentPrice: number;
  isEnable: number;
  isInitDayData: number;
  dayCount: number;
  createTime: string;
  updateTime: string;

  list: StockNowTime[];
}

interface StockNowTime {
  timeRecord: string;
  increase: number;
}

interface StockDataRecord { 
  id: number;
  dateTime: string;
  name: string;
  code: string;
  minuteCount: number;
  secondCount: number;
  intA:number;
}

const onInputChange = (newValue, oldValue) => {
  console.log("Input changed:", newValue);
  const containsChinese = /[\u4e00-\u9fa5]/.test(newValue);
  if (containsChinese) {
    onSearh(newValue, 2);
  } else if (newValue.length == 6) {
    onSearh(newValue, 1);
  }
};


const handleDateChange = (val) => {
    console.log('选择了新的日期/时间:', val);
    const date = new Date(val)
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2); // 月份是从0开始的，所以需要加1
    const day = ('0' + date.getDate()).slice(-2);
    const dayTime = `${year}-${month}-${day}`;
    console.log('选择了新的日期/时间:', dayTime);
    formInline.dateTime = dayTime;
};

const loading = ref(false);
const tableRef = ref<TableInstance>();

const tableData = ref([]);
const tableDataRecordData = ref([]);
const tableDataIndustryStockList = ref([]);

const store = useStore();
const handleEdit = (index: number, row: StockName) => {
  console.log(index, row)
  if (row.focus == 0) {
    row.focus = 1;
  } else if (row.focus == 1) {
    store.dispatch('changeStockCode', row.code);
    store.dispatch('changeStockName', row.name);
    console.log("股票代码" + store.state.stockCode);
    row.focus = 2;
  } else if (row.focus == 2) {
    row.focus = 3;
  }else if (row.focus == 3) {
    row.focus = 0;
  }
  onUpdateFoucus(row.id, row.focus);
}

const industry_type = [ { value: 0,label: 'A股指数', },
                { value: 1,label: '指数', },
                { value: 2,label: '证券' },
                { value: 3,label: '半导体' },
                { value: 4,label: '互联网电商' }]
 const industry_type_str = ["A股指数", "指数", "证券","半导体","互联网电商"]                
const handleSelectIndustry = (value) => {
      formInline.industry_type_index = parseInt(value);
}

var code = ''
onMounted(() => {
      // fetchData();
      formInline.dateTime = getToday()

      const clipboard = new ClipboardJS('.btn-copy', {
        text: () => code
      });

      clipboard.on('success', (e) => {
        console.log('Text copied to clipboard');
        e.clearSelection();
      });

      clipboard.on('error', (e) => {
        console.error('Failed to copy text: ', e);
      });
    });

const  handleCopy = (index: number, row: StockName) => {
  console.log(index, row)
  code = row.code
}

const handlerAddIndustry = (index: number, row: StockName) => {
  var industry = industry_type_str[formInline.industry_type_index];
  axios.post("api/plat/stockIndustry/add", {
    industryType:industry,
    code:row.code,
    name:row.name
  }).then((response) => {
    console.log(response);
    if (response.data.status == 200) {
        ElMessage({
          message: "添加成功",
          type: "warning",
        });
      } else {
        ElMessage({
          message: response.data.message,
          type: "warning",
        });
      }
  })
}


const getToday = () =>  {
      const today = new Date();
      const year = today.getFullYear();
      const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以要加1
      const day = String(today.getDate()).padStart(2, '0');

      return `${year}-${month}-${day}`;
    }
</script>
  



<style>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>